<?php

namespace src;

use src\bootstrap\BootProviders;
use src\bootstrap\LoadConfiguration;
use src\bootstrap\RegisterFacades;
use src\bootstrap\RegisterProviders;

class HttpKernel
{
    /**
     * @var Application
     */
    protected $app;

    /**
     * @var Router
     */
    protected $router;

    /*
     * 引导类
     */
    protected $bootstrappers = [
        RegisterFacades::class,
        LoadConfiguration::class,
        RegisterProviders::class,
        BootProviders::class,
    ];

    protected $middlewares = [];

    public function __construct(Application $app, Router $router)
    {
        $this->app = $app;
        $this->router = $router;
    }

    /**
     * @param $request
     * @return mixed|Response
     */
    public function handle($request)
    {
        return $this->sendRequestThroughRouter($request);
    }

    /**
     * 请求流程
     * @param $request
     * @return mixed
     */
    protected function sendRequestThroughRouter($request)
    {
        $this->app->instance('request', $request);
        $this->bootstrap();
        return (new Pipeline($this->app))
            ->send($request)
            ->through($this->middlewares ?? [])
            ->then($this->dispatchToRouter());
    }

    //执行引导程序
    protected function bootstrap()
    {
        $this->app->bootstrapWith($this->bootstrappers);
    }

    protected function dispatchToRouter()
    {
        return function ($request) {
            $this->app->instance('request', $request);
            return $this->router->dispatch($request);
        };
    }
}